/**
 * @FileName: PackageController.java
 * @Author
 * @Description:
 * @Date 2016年1月11日 下午4:31:23
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.LocalizedConfig;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.service.PackageLocalizedConfigService;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Package;
import cn.hpclub.server.service.PackageService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ResultCode;
import cn.hpclub.server.validator.admin.PackageValidator;

// @ControllerBind(controllerKey = "package")
public class PackageController extends BaseAdminController<Package>{
    private static final Logger logger       = LoggerFactory.getLogger(PackageController.class);

    // 前后端Key
    static String               IF_EDIT      = "edit";                                          // UI编辑标识
    private static final String HTML_LIST    = "/admin/package_list.tpl";
    public static final String  HTML_ADD     = "/admin/package_add.tpl";
    private static final String URL_LIST     = "/package/list";
    private static final String ID           = "id";
    public static final String  NAME         = "name";
    public static final String  CHARGE       = "charge";
    public static final String  CODE         = "code";
    private static final String DESC         = "desc";
    private static final String DETAILS      = "details";
    private static final String SORT      = "sort";
    public static final String  PREDEPOSITED = "predeposited";
    private static final String TYPE         = "type";
    private static final String EDIT         = "0";
    private static final String ADD          = "1";

    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();;
        String select = "select id,name,type,localized,( SELECT GROUP_CONCAT(DisplayName) AS a FROM ( SELECT localized_city_id, business_id FROM localized_config WHERE localized_config.business = "+LocalizedConfig.TYPE_PACKAGE_XHRW+" ) AS localized_cities LEFT JOIN organization org ON org.id = localized_cities.localized_city_id WHERE localized_cities.business_id = package.id ) AS cities,tariff_code,brand_id,format(monthly_charge,2) as monthly_charge,format(predeposited,2) as predeposited,summary,created_time ,(select real_name from sys_user where sys_user.id = package.created_by)as creater_name,(select DisplayName from organization where organization.id = package.org_id) as creater_org,enabled,sort ";

        findByPageForSearch(select, PackageService.service.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);

        // 页面是否显示"营销活动选号入网"类型
        if(isPackageTypeShow()){
            setAttr("isShow", "1");
        }

        render(HTML_LIST);
    }

    public void export(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();;
        List<Record> listExport = PackageService.service.getListExport(searchInfo);
        PoiRender excel = PoiRender.me(listExport);
        String[] headesExport = PackageService.headesExport;
        String[] columnsExport = PackageService.columnsExport;

        render(excel.sheetName("选号套餐配置").headers(headesExport).columns(columnsExport).fileName(generateFileName()));
    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String curTime = sdf.format(date);
        String fileName = "选号套餐配置-" + curTime + ".xlsx";
        // System.out.println("excel file name:" + fileName);
        try {
            return new String(fileName.getBytes("gbk"),"iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public void delete(){

//        String[] ids = getParaValues(Constant.IDS);
        Integer[] ids = getParaValuesToInt(Constant.IDS);
        logger.debug("Package delete ids.len:" + ids.length);

        /*
         * 由于唯一性问题先屏蔽掉：String[] codes =
         * PackageService.service.findCodesByIds(ids);
         * BusinessService.service.deleteByCodes(codes);
         */

        ResultCode result = PackageService.service.delete(ids);

        if(result == ResultCode.SUCCESS){
            //删除成功后，需要删除localized_config的数据和business_auth_config，spread_member_auth_config关于该资费的所有数据。避免脏数据
            PackageLocalizedConfigService.service.deleteConfig(ids);

            ajaxJsonSuccessMessage(Constant.Msg.DEL_DONE);
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        }
    }

    public void edit(){
        add();
    }

    public void add(){
        if(getParaToInt(IF_EDIT, 0) == 1){
            toEdit();
        } else{
            toAdd();
        }
        setAttr(IF_EDIT, getParaToInt(IF_EDIT, 0));

        // 页面是否显示"营销活动选号入网"类型
        if(isPackageTypeShow()){
            setAttr("isShow", "1");
        }

        if(InterfaceUtil.isOrgChengdu(InterfaceUtil.getOrgId())
                || (InterfaceUtil.getOrgId() == InterfaceUtil.getIdTop()) || (InterfaceUtil.getAdminId() == 1)){
            setAttr("isShow", "1");
        }
        render(HTML_ADD);
    }

    /**
     * @Title: isPackageTypeShow
     * @Description:页面是否显示"营销活动选号入网"类型
     * @return boolean
     */
    private boolean isPackageTypeShow(){
        // 如果当前登录的用户org属于成都或者是dzgadmin或者是admin，则显示"营销活动选号入网"选项
        int orgId = InterfaceUtil.getOrgId();
        if(InterfaceUtil.isOrgChengdu(orgId) || (orgId == InterfaceUtil.getIdTop())
                || (InterfaceUtil.getAdminId() == 1)){
            return true;
        }

        return false;
    }

    public void toAdd(){
        setAttr(ID, 0);
        List<Organization> cities = Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
        setAttr("cities", cities);
    }

    /*
     * 编辑
     */
    public void toEdit(){
        String id = getPara(ID, "");
        Package pkg = Package.dao.findById(id);
        ConcurrentHashMap<String, String> map = fromDO(pkg);

        int localized = pkg.getInt(Package.LOCALIZED);
        setAttr("localized", localized);

        List<Organization> cities = Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
        setAttr("cities", cities);
//        map.put("cities",cities);
        List<LocalizedConfig> configs = LocalizedConfig.dao.findByBusinessAndId(LocalizedConfig.TYPE_PACKAGE_XHRW,id);
        setAttr("localizedConfig", configs);
//        map.put("localizedConfig",configs);

        setAttrs(map);

        // 熊诗言：修改的时候找到business的id同时修改它
        /*
         * 由于唯一性问题先屏蔽掉：Integer businessId =
         * BusinessService.service.findBusinessByCode(pkg.getStr(Package.
         * TARIFF_CODE)).getInt(Business.ID); setAttr("businessId", businessId);
         */
    }

    /**
     * @Title: fromDO
     * @Description:TODO
     * @param pkg
     * @return ConcurrentHashMap<String,String>
     */

    private ConcurrentHashMap<String, String> fromDO(Package pkg){
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
        map.put(NAME, pkg.getStr(Package.NAME));
        String charge = String.format("%.2f", pkg.getDouble(Package.MONTHLY_CHARGE));
        map.put(CHARGE, charge);
        String code = pkg.getStr(Package.TARIFF_CODE);
        map.put(CODE, code);
        map.put(ID, String.valueOf(pkg.getInt(Package.ID)));
        String summary = pkg.getStr(Package.SUMMARY);
        map.put(DESC, summary == null ? "" : summary);
        String details = pkg.getStr(Package.DETAILS);
        map.put(DETAILS, details == null ? "" : details);
        String predeposited = String.format("%.2f", pkg.getDouble(Package.PREDEPOSITED));
        map.put(PREDEPOSITED, predeposited);
        map.put(TYPE, String.valueOf(PackageService.service.convertFromDBType(pkg.getInt(Package.TYPE))));
        String brandId = pkg.getStr(Package.BRAND_ID);
        map.put(Package.BRAND_ID, brandId != null ? brandId : "");
        String enabled = String.valueOf(pkg.getInt("enabled"));


        String sort = pkg.getInt(Package.SORT)+"";
        map.put(Package.SORT, sort != null ? sort : "0");

        return map;
    }

    @Before({ PackageValidator.class, Tx.class })
    public void update() {
        boolean isAdd = !getPara(IF_EDIT, EDIT).equals(ADD); //保留原来的逻辑

        Package pkg = addOrUpdate(isAdd);

        redirect(URL_LIST);
    }






    /**
     * @param isAdd
     * @return
     */
    private Package addOrUpdate(boolean isAdd)  {
        Package model = new Package();
        String name = getPara(NAME, "");// 套餐名称
        String desc = getPara(DESC, "");// 特点描述
        String details = getPara(DETAILS, "");// 详情
        Integer type = getParaToInt(TYPE, null);// 类型

        String charge = getPara(CHARGE, "0");// 资费
        String predeposited = getPara(PREDEPOSITED, "0.00");// 预存费用
        String code = getPara(CODE, "");// 资费代码
        String brandId = getPara(Package.BRAND_ID, "");


        int localized = getParaToInt("localized", 0);//默认为非属地化
        int oldLocalized = LocalizedConfig.LOCALIZED_UNIFIED;

        int sort = getParaToInt(SORT, 0);// 排序字段


        Date now = new Date();
        model.set(Package.NAME, name).set(Package.SUMMARY, desc).set(Package.DETAILS, details)
                .set(Package.TYPE, PackageService.service.convertToDBType(type)).set(Package.MONTHLY_CHARGE, charge)
                .set(Package.PREDEPOSITED, predeposited).set(Package.TARIFF_CODE, code)
                .set(Package.LAST_UPDATED_TIME, now).set(Package.BRAND_ID, brandId).set(Package.LOCALIZED, localized).set(Package.SORT, sort);

        if(isAdd){
            int org_id = InterfaceUtil.getOrgId();// 当前用户机构id
            int creator = InterfaceUtil.getAdminId();// 当前用户id
            model.set(Package.CREATED_TIME, now).set(Package.ORG_ID, org_id).set(Package.CREATED_BY, creator)
                    .set("enabled", 0);
            model.save();
        } else{
            Integer id = getParaToInt(ID, null);
            oldLocalized = Package.dao.findById(id).getInt(Package.LOCALIZED);
            model.set(Package.ID, id);
            model.update();
        }

        int  pkgId = model.getInt(Package.ID);

        PackageLocalizedConfigService.service.saveLocalizedConfig(pkgId,localized,!isAdd,oldLocalized, getParaValuesToInt("city_ids"));

        // 同时修改business的
        // 由于唯一性问题先屏蔽掉：BusinessService.service.updateCodeAndName(pkg.getStr(Package.TARIFF_CODE),
        // pkg.getStr(Package.NAME), getPara("businessId"));

        return model;
    }

    public void enable(){
        enablePackage(1, "启用");
    }

    public void disable(){
        enablePackage(0, "禁用");
    }

    private void enablePackage(int enabled, String actionName){
        logger.info("enabled=" + enabled);
        String[] ids = getParaValues("ids");

        StringBuffer sb = new StringBuffer();
        sb.append("UPDATE package SET enabled = " + enabled + ",last_updated_time='"
                + DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss") + "' WHERE id IN (");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
            return;
        }
        boolean success = Db.update(sb.toString(), (Object[])ids) > 0;
        if(success){
            ajaxJsonSuccessMessage(actionName + "成功");
        } else{
            ajaxJsonErrorMessage(actionName + "失败");
        }
    }

}
